#include"config.h"

#include<iostream>


void Config::trim(std::string& str)
{
    int start=str.find_first_not_of(' ');
    int end=str.find_last_not_of(' ');
    str=str.substr(start,end-start+1);
}

//加载配置文件
void Config::LoadConfigFile(const char* file)
{
    FILE* f=fopen(file,"r");
    if(f == NULL) 
    {
        std::cerr << "config file not exist" << std::endl; 
        exit(EXIT_FAILURE);
    }
    while(!feof(f))
    {
        char buf[512]={0};
        fgets(buf,512,f);
        std::string str(buf);
        trim(str);
        if(str[0]=='#')
        {
            continue;
        }
        int index=str.find('=' );
        if(index==-1)
        {
            continue;
        }
        std::string key=str.substr(0,index);
        trim(key);
        std::string value;
        if(str[str.size()-1]=='\n')
            value=str.substr(index+1,str.size()-index-2);
        else
            value=str.substr(index+1,str.size()-index-1);
        trim(value);
        _congfigMap.insert({key,value});
    }
    fclose(f);
}

//查询配置项信息
std::string  Config::GetItem(const std::string& key)
{
    if(_congfigMap.count(key))
    {
        return _congfigMap.find(key)->second;
    }
    return "";
}